use commands::request;
use tauri::{
    plugin::{Builder, TauriPlugin},
    Manager, Runtime,
};

pub use models::*;

#[cfg(desktop)]
mod desktop;

mod commands;
mod error;
mod models;

pub use error::{Error, Result};

#[cfg(desktop)]
use desktop::Api;

/// Extensions to [`tauri::App`], [`tauri::AppHandle`] and [`tauri::Window`] to access the api APIs.
pub trait ApiExt<R: Runtime> {
    fn api(&self) -> &Api;
}

impl<R: Runtime, T: Manager<R>> crate::ApiExt<R> for T {
    fn api(&self) -> &Api {
        self.state::<Api>().inner()
    }
}

/// Initializes the plugin.
pub fn init<R: Runtime>() -> TauriPlugin<R> {
    Builder::new("api")
        .setup(|app, _api| {
            #[cfg(desktop)]
            let api = desktop::init()?;
            app.manage(api);
            Ok(())
        })
        .invoke_handler(tauri::generate_handler![request])
        .build()
}
